package com.gome.axwl.aoc.facade.impl;

import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.common.util.UrlFilesToZipUtil;
import com.gome.axwl.aoc.entity.driver.TakesendTaskSpeech;
import com.gome.axwl.aoc.entity.dto.QueryAllotTaskDto;
import com.gome.axwl.aoc.entity.dto.TaskJobSearchDto;
import com.gome.axwl.aoc.entity.dto.TruckListSearchDto;
import com.gome.axwl.aoc.entity.po.QueryAllotTaskPo;
import com.gome.axwl.aoc.entity.po.TaskJobSearchPo;
import com.gome.axwl.aoc.entity.po.TruckListSearchPo;
import com.gome.axwl.aoc.facade.TruckFacade;
import com.gome.axwl.aoc.service.TruckService;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class TruckFacadeImpl implements TruckFacade {

    private final static Logger log = LoggerFactory.getLogger(TruckFacadeImpl.class);

    @Autowired
    TruckService truckService;

    /**
     * 模糊查询司机
     *
     * @param keyword
     * @return
     */
    @Override
    public Object getDriverByKeyword(String keyword, String dcId) {
        return truckService.getDriverByKeyword(keyword, dcId);
    }

    /**
     * 分页查询车次列表
     *
     * @param truckListSearchDto
     * @return
     */
    @Override
    public ResultData getTruckList(TruckListSearchDto truckListSearchDto) {
        TruckListSearchPo truckListSearchPo = BeanJsonUtil.beanConvert(truckListSearchDto, TruckListSearchPo.class);
        return truckService.getTruckList(truckListSearchPo);
    }

    /**
     * 分页查询任务单列表
     *
     * @param taskJobSearchDto
     * @return
     */
    @Override
    public ResultData getTaskJobList(TaskJobSearchDto taskJobSearchDto) {
        TaskJobSearchPo taskJobSearchPo = BeanJsonUtil.beanConvert(taskJobSearchDto, TaskJobSearchPo.class);
        return truckService.getTaskJobList(taskJobSearchPo);
    }

    /**
     * 下载评价文件
     *
     * @param taskNo
     */
    @Override
    public ResultData filesDownloadToZip(String taskNo, HttpServletResponse response) {
        try {
            //获取语音文件对象列表
            ResultData<List<TakesendTaskSpeech>> listResultData = truckService.filesDownloadToZip(taskNo);
            if (!listResultData.getCode().equals(ErrorCode.SUCCESS)) {
                return listResultData;
            }
            if (CollectionUtils.isEmpty(listResultData.getData())) {
                return ResultData.newResultData(ErrorCode.QUERY_FAILOR, "语音评价文件地址为空");
            }
            log.info("--------语音评价列表类容为:{}", listResultData.getData());
            List<TakesendTaskSpeech> takesendTaskSpeechList = listResultData.getData();
            //控制文件名编码
            String filename ="语音评价.zip";
            log.info("filesDownloadToZip filename:{}",filename);
            List<String> urlList = new ArrayList<String>();
            for (TakesendTaskSpeech tts : takesendTaskSpeechList) {
                urlList.add(tts.getUrl());
            }
            //下载文件列表
            return downloadFileByUrl(filename, urlList, response);
        } catch (Exception e) {
            log.error("语音评价文件下载失败", e);
            return ResultData.newResultData(ErrorCode.FAILOR, "语音评价文件下载失败");
        }
    }


    /**
     * 下载评价文件
     * <p>
     * //@param taskNo
     */
   /* @Deprecated
    @Override
    public ResultData filesDownloadToZip(String taskNo, HttpServletResponse response) {
        try {
            ResultData<List<TakesendTaskSpeech>> listResultData = truckService.filesDownloadToZip(taskNo);      //获取语音文件对象列表
            if (!listResultData.getCode().equals(ErrorCode.SUCCESS)) {
                return listResultData;
            }
            if (CollectionUtils.isEmpty(listResultData.getData())) {
                return ResultData.newResultData(ErrorCode.QUERY_FAILOR, "语音评价文件地址为空");
            }
            log.info("--------语音评价列表类容为:{}", listResultData.getData());
            List<TakesendTaskSpeech> takesendTaskSpeechList = listResultData.getData();
            String filename = new String("语音评价.zip".getBytes("UTF-8"), "ISO8859-1");//控制文件名编码
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            UrlFilesToZipUtil s = new UrlFilesToZipUtil();
            int idx = 1;
            for (TakesendTaskSpeech tts : takesendTaskSpeechList) {
                String fileUrl = tts.getUrl();
                String fileName = null;
                if (null == fileUrl || fileUrl.trim().length() == 0 || !fileUrl.startsWith("http")) {
                    return ResultData.newResultData(ErrorCode.QUERY_FAILOR, "语音评价文件地址为空");
                }
                if (null == fileName || fileName.trim().length() == 0) {
                    fileName = UUID.randomUUID().toString() + "." + getExtensionName(fileUrl);
                }
                zos.putNextEntry(new ZipEntry(fileName));
//                byte[] bytes = s.getImageFromURL(fileUrl);
                byte[] bytes = httpConverBytes(fileUrl);
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
                idx++;
            }
            zos.close();
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
            OutputStream os = response.getOutputStream();
            os.write(bos.toByteArray());
            os.close();
            return ResultData.newSuccessResultData();
        } catch (Exception e) {
            log.error("语音评价文件下载失败", e);
            return ResultData.newResultData(ErrorCode.FAILOR, "语音评价文件下载失败");
        }
    }*/
    @Override
    public ResultData queryTakesendTask(QueryAllotTaskDto queryTakesendTaskDto) {
        QueryAllotTaskPo taskJobSearchPo = BeanJsonUtil.beanConvert(queryTakesendTaskDto, QueryAllotTaskPo.class);
        return truckService.queryTakesendTask(taskJobSearchPo);
    }

    @Override
    public ResultData queryTakesendDetail(Long takesendId) {
        return truckService.queryTakesendDetail(takesendId);
    }

    /**
     * @param path
     * @return
     * @MethodName httpConverBytes
     * @Description http路径文件内容获取
     */
    public byte[] httpConverBytes(String path) {
        BufferedInputStream in = null;
        ByteArrayOutputStream out = null;
        URLConnection conn = null;

        try {
            URL url = new URL(path);
            conn = url.openConnection();

            in = new BufferedInputStream(conn.getInputStream());

            out = new ByteArrayOutputStream(1024);
            byte[] temp = new byte[1024];
            int size = 0;
            while ((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            byte[] content = out.toByteArray();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getExtensionName(String filename) {
        if (filename != null && filename.length() > 0) {
            int dot = filename.lastIndexOf('.');
            if (dot > -1 && dot < filename.length() - 1) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    @Override
    public ResultData downloadFileByUrl(String fileName, List<String> urlList, HttpServletResponse response) {
        try {
            //控制文件名编码
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            UrlFilesToZipUtil s = new UrlFilesToZipUtil();
            int idx = 1;
            for (String url : urlList) {
                String fileUrl = url;
                String fileItemName = null;
                if (null == fileUrl || fileUrl.trim().length() == 0 || !fileUrl.startsWith("http")) {
                    log.info("语音评价文件地址为空");
                    continue;
                }
                if (null == fileItemName || fileItemName.trim().length() == 0) {
                    //生成随机文件名
                    fileItemName = UUID.randomUUID() + "." + idx + "." + getExtensionName(fileUrl);
                }
                zos.putNextEntry(new ZipEntry(fileItemName));
//              byte[] bytes = s.getImageFromURL(fileUrl);
                byte[] bytes = httpConverBytes(fileUrl);
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
                idx++;
            }
            zos.close();
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream os = response.getOutputStream();
            os.write(bos.toByteArray());
            os.close();
            return ResultData.newSuccessResultData();
        } catch (Exception e) {
            log.error("IOException", e);
            return ResultData.newResultData(ErrorCode.FAILOR, "语音评价文件下载失败");
        }
    }

}
